package com.tomato.controller;

import com.tomato.dto.Result;
import com.tomato.dto.RecordQueryDTO;
import com.tomato.dto.TodoRecordDTO;
import com.tomato.dto.TodoRecordSyncDTO;
import com.tomato.entity.TodoRecord;
import com.tomato.service.TodoRecordService;
import com.tomato.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/record")
@Tag(name = "待办记录", description = "待办完成记录管理接口")
public class TodoRecordController {
    private final TodoRecordService todoRecordService;
    private final JwtUtil jwtUtil; // 注入JwtUtil

    public TodoRecordController(TodoRecordService todoRecordService, JwtUtil jwtUtil) {
        this.todoRecordService = todoRecordService;
        this.jwtUtil = jwtUtil;
    }

    @Operation(summary = "创建待办记录")
    @PostMapping
    public Result<TodoRecord> createRecord(
            @RequestHeader("Authorization") String token,
            @RequestBody TodoRecordDTO recordDTO) {
        Long userId = jwtUtil.getUserIdFromToken(token.replace("Bearer ", ""));
        log.debug("Create todo record request for user: {}", userId);
        TodoRecord record = todoRecordService.createRecord(userId, recordDTO);
        return Result.success(record);
    }

    @Operation(summary = "上传待办记录（增量）")
    @PostMapping("/upload")
    public Result<Void> uploadRecords(
            @RequestHeader("Authorization") String token,
            @Valid @RequestBody List<TodoRecordSyncDTO> syncDTOs) {
        Long userId = jwtUtil.getUserIdFromToken(token.replace("Bearer ", ""));
        log.debug("Upload todo records request for user: {} with {} records", userId, syncDTOs.size());
        todoRecordService.uploadRecords(userId, syncDTOs);
        return Result.success();
    }

    @Operation(summary = "查询待办记录")
    @GetMapping("/query")
    public Result<List<TodoRecord>> queryRecords(
            @RequestHeader("Authorization") String token,
            RecordQueryDTO queryDTO) {
        Long userId = jwtUtil.getUserIdFromToken(token.replace("Bearer ", ""));
        log.debug("Query todo records request for user: {} between {} and {}",
                userId, queryDTO.getStartDate(), queryDTO.getEndDate());
        List<TodoRecord> records = todoRecordService.queryRecords(userId, queryDTO);
        return Result.success(records);
    }
}